package com.fz.song.feibao.framework.exceptions;

import cn.dev33.satoken.exception.NotLoginException;
import com.fz.song.feibao.framework.common.enums.CodeEnum;
import com.fz.song.feibao.framework.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 全局异常处理器
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionProcessor {

    @ExceptionHandler(value = Exception.class)
    public R errorHandler(ServerException ex) {
        return R.fail(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler(value = ServerException.class)
    public R serverExceptionHandler(ServerException ex) {
        return R.fail(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler(value = NotLoginException.class)
    public R notLoginExceptionHandler(NotLoginException ex) {

        // 判断场景值，定制化异常信息
        String message = "";
        if (ex.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        } else if (ex.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (ex.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else if (ex.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token已被顶下线";
        } else if (ex.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token已被踢下线";
        } else {
            message = "当前会话未登录";
        }
        int code = CodeEnum.NOT_LOGIN_ERROR.getCode();
        String msg = CodeEnum.NOT_LOGIN_ERROR.getMsg();
        return R.fail(code, msg + ":" + message);
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleBindGetException(MethodArgumentNotValidException ex) {
        // 获取所有异常
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());
        return R.fail(CodeEnum.PARAM_ERROR.getCode(), CodeEnum.PARAM_ERROR.getMsg() + ":" + String.join(",", errors));
    }


}
